package com.ruoyi.standingbook.v2toilet.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.standingbook.v2toilet.MapBean;
import com.ruoyi.standingbook.v2toilet.domain.V2Toilet;
import com.ruoyi.standingbook.v2toilet.domain.bo.V2ToiletBo;
import com.ruoyi.standingbook.v2toilet.domain.vo.V2ToiletImpDetailVo;
import com.ruoyi.standingbook.v2toilet.domain.vo.V2ToiletVo;
import com.ruoyi.standingbook.v2toilet.mapper.V2ToiletBillMapper;
import com.ruoyi.standingbook.v2toilet.mapper.V2ToiletMapper;
import com.ruoyi.standingbook.v2toilet.service.IToiletImpDetailService;
import com.ruoyi.standingbook.v2toilet.service.IToiletService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * V2市政公厕管养Service业务层处理
 *
 * @author cc
 * @date 2023-06-07
 */
@RequiredArgsConstructor
@Service
public class V2ToiletServiceImpl implements IToiletService {

    private final V2ToiletMapper baseMapper;
    private final IToiletImpDetailService iToiletImpDetailService;
    private final V2ToiletBillMapper toiletBillMapper;

    /**
     * 查询V2市政公厕管养
     */
    @Override
    public V2ToiletVo queryById(String id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询V2市政公厕管养列表
     */
    @Override
    public TableDataInfo<V2ToiletVo> queryPageList(V2ToiletBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<V2Toilet> lqw = buildQueryWrapper(bo);
        Page<V2ToiletVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询V2市政公厕管养列表
     */
    @Override
    public List<V2ToiletVo> queryList(V2ToiletBo bo) {
        LambdaQueryWrapper<V2Toilet> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<V2Toilet> buildQueryWrapper(V2ToiletBo bo) {
        LambdaQueryWrapper<V2Toilet> lqw = Wrappers.lambdaQuery();
        //时间区间查询
        Map<String, Object> params = bo.getParams();
        lqw.between(params.get("beginCreateDate") != null && params.get("endCreateDate") != null, V2Toilet::getCreateDate, params.get("beginCreateDate"), params.get("endCreateDate"));
        lqw.like(StringUtils.isNotBlank(bo.getCommunity()), V2Toilet::getCommunity, bo.getCommunity());
        lqw.like(StringUtils.isNotBlank(bo.getToiletName()), V2Toilet::getToiletName, bo.getToiletName());
        lqw.like(StringUtils.isNotBlank(bo.getToiletName()), V2Toilet::getToiletName, bo.getToiletName());
        return lqw;
    }

    /**
     * 新增V2市政公厕管养
     */
    @Override
    public Boolean insertByBo(V2ToiletBo bo) {
        V2Toilet add = BeanUtil.toBean(bo, V2Toilet.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改V2市政公厕管养
     */
    @Override
    public Boolean updateByBo(V2ToiletBo bo) {
        V2Toilet update = BeanUtil.toBean(bo, V2Toilet.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(V2Toilet entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除V2市政公厕管养
     */
    @Override
    @Transactional
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        //        return baseMapper.deleteBatchIds(ids) > 0;
        toiletBillMapper.realDelByToiletIds(ids);
        return baseMapper.realDelByIds(ids) > 0;
    }

    @Override
    public boolean batchInsertOrUpdate(List<V2ToiletImpDetailVo> detailBo) {
        List<V2Toilet> list = BeanCopyUtils.copyList(detailBo, V2Toilet.class);
        if (list != null) {
            list.forEach(BaseEntity::restBase);
            return this.baseMapper.insertOrUpdateBatch(list);
        }
        return false;
    }

    /**
     * @param map 包含excel中的管养日期
     * @return 已经发生变化的数据
     */
    @Override
    public List<String> listChanged(Map<String, Object> map) {
        return this.baseMapper.listChanged(map);
    }

    @Override
    public List<V2ToiletVo> reportDetail(V2ToiletBo bo) {

        return this.queryList(bo);
    }


    //    @Override
    //    public List<V2ToiletVo> monthReport(V2ToiletBo bo) {
    //        if (Objects.isNull(bo.getCreateDate()))
    //            bo.setCreateDate(new Date());
    //        Map<String, Object> queryMap = new HashMap<>();
    //        queryMap.put("beginCreateDate", DateUtil.beginOfMonth(bo.getCreateDate()));
    //        queryMap.put("endCreateDate", DateUtil.endOfMonth(bo.getCreateDate()));
    //        bo.getParams().putAll(queryMap);
    //        LambdaQueryWrapper<V2Toilet> lqw = buildQueryWrapper(bo);
    //        return baseMapper.selectVoList(lqw);
    //    }

    /**
     * 下拉选项（社区和公厕查询条件）
     *
     * @return value
     */
    @Override
    public Map<String, List<MapBean<String>>> selectCondition() {

        List<MapBean<String>> items = this.baseMapper.selectCondition();
        System.out.println(JSONUtil.toJsonPrettyStr(items));
        //select t.community, MD5(t.community) as communityCode, t.id as toiletCode, t.toilet_name as toiletName
        Map<String, List<MapBean<String>>> map = items.stream()
            .collect(Collectors.groupingBy(item -> String.valueOf(item.get("communityCode")), HashMap::new, Collectors.toList()));
        System.out.println(JSONUtil.toJsonPrettyStr(map));
        return map;
    }

    @Override
    public List<V2ToiletVo> queryListByDate(String date) {
        LambdaQueryWrapper<V2Toilet> lqw = Wrappers.lambdaQuery();
        lqw.eq(V2Toilet::getCreateDate,date);
        return baseMapper.selectVoList(lqw);
    }


}
